<template>
	<div class="invite-members-container">
		<Modal title="" v-model="dialogVisibleInviteMembers" class-name="content-modal" @on-cancel="cancel" :mask-closable="false">
			<div class="head-box">
				<span class="title">邀请成员</span>
				<p class="subtitle">
					<span>SessionID：</span>
					<span>{{ sessionId }}</span>
				</p>
				<p class="reuse-text">
					<span>链接是否重复使用</span>
					<i-switch v-model="form.isReuseSwitch" class="switch"></i-switch>
				</p>
			</div>
			<Form ref="formValidate" :model="form" :rules="ruleValidate" class="form-box">
				<Form-item label="" prop="userName">
					<p class="text-box">
						<span class="title-name">访客名</span>
						<span class="not-required">（非必填）</span>
					</p>
					<Input type="text" v-model="form.userName" placeholder="请输入访客名" class="input-background" :maxlength="userInputlength"> </Input>
				</Form-item>
				<Form-item label="" prop="role" style="margin-top: -14px;"  :rules="[{ required: true, message: '*请选择访客角色'}]">
					<p class="text-box">
						<span class="title-name">访客角色</span>
						<!-- <span class="not-required">（非必填）</span> -->
					</p>
					<Select v-model="form.role" placeholder="请选择访客角色">
						<Option v-for="item in roleList" :value="item.name" :key="item.name">{{ item.name }}</Option>
					</Select>
					<!-- <Input type="text" v-model="form.role" placeholder="请输入访客角色" class="input-background" :maxlength="roleInputlength"> </Input> -->
				</Form-item>
				<Form-item label="" style="margin-top: 14px;">
					<p class="text-box">
						<span class="title-name">链接有效期</span>
						<span class="not-required">（非必填）</span>
					</p>
					<Row>
						<Col span="11">
							<Date-picker type="datetime" placeholder="开始时间" style="width: 100%;" class="dataTime-input-background" v-model="form.startTime"></Date-picker>
						</Col>
						<Col span="2" style="text-align: center;margin-top: 4px;">-</Col>
						<Col span="11">
							<Date-picker type="datetime" placeholder="结束时间" style="width: 100%;" class="dataTime-input-background" v-model="form.endTime"></Date-picker>
						</Col>
					</Row>
				</Form-item>
				<Form-item label="" prop="link" style="margin: -8px 0 0 0;">
					<Input type="text"  v-model="form.link" placeholder="链接生成区" :class="form.link ? 'active-font' : 'input-link'" disabled> </Input>
				</Form-item>
				<Form-item v-if="form.link" class="copy-content">
					<Button id="copyBtn" ref="copyBtn" class="copy-btn" @click="onCopy" :disabled="form.link ? false : true">一键复制</Button>
				</Form-item>
			</Form>
			<div slot="footer">
				<span @click="cancel" class="colse-btn">取消</span>
				<span class="vertical-line"></span>
				<span @click="ok" :class="loadingStatus !== 'idle' ? 'grey-btn' : 'link-btn'" :disabled="loadingStatus === 'loading' || 'success'">{{ loadingStatus !== 'success' ? '链接生成' : '已生成' }}</span>
			</div>
			<div class="loading-box">
				<Spin fix v-if="loadingStatus === 'loading'" class="demo-spin-col">
					<template slot="">
						<Icon type="load-d" class="demo-spin-icon-load"></Icon>
						<div class="load-text">生成中</div>
					</template>
				</Spin>
			</div>
		</Modal>
	</div>
</template>

<script>
import ClipboardJS from 'clipboard';
import { getScenariosRoles } from '../api/api';
export default {
	data() {
		return {
			dialogVisibleInviteMembers: false,
			form: {
				isReuseSwitch: true,
				userName: '',
				role: '',
				startTime: '',
				endTime: '',
				link: ''
			},
			ruleValidate: {
				userName: [],
				role: []
			},
			userInputlength: 20,
			roleInputlength: 16,
			spinShow: false,
			loadingStatus: 'idle',
			roleList:[]
		};
	},
	computed: {
		inviteCode: function() {
			return this.createInviteCode;
		}
	},
	watch: {
		inviteCode: function(newval, oldval) {
			console.log('inviteCode', newval, oldval);
			let path = '/?inviteCode=';
			// eslint-disable-next-line no-undef
			if(process.env.NODE_ENV === 'production'){
                path = '/customer/#/start?inviteCode=';
			}
			this.form.link = window.location.origin + path + newval + '&org=' + localStorage.getItem('org');
		}
	},
	props: ['showinvteModelView', 'sessionId', 'createInviteCode'],
	mounted() {
		this.dialogVisibleInviteMembers = this.showinvteModelView;
		if(sessionStorage.getItem('roleList')){
			this.roleList =  JSON.parse(sessionStorage.getItem('roleList'))
		}
		this.getScenariosRolesWithId(sessionStorage.getItem('service'));
	},
	methods: {
		/**
		 * 根据业务场景id获取所有的访客角色
		 * @param {string} scenId 
		 */
		getScenariosRolesWithId(scenId){
			this.$Spin.show();
            return new Promise((resolve,reject)=>{
                  getScenariosRoles(scenId).then((resp)=>{
					console.log('getScenariosRoles result',resp);
					if(resp.data && resp.data.data && resp.data.data.length > 0){
						this.roleList = resp.data.data;
						console.log('getScenariosRoles roleList',this.roleList);
						sessionStorage.setItem('roleList',JSON.stringify(this.roleList));
						resolve(resp.data.data);
					}else{
						this.$Message.error('当前业务场景下无角色');
                        reject();
					}
					this.$Spin.hide();
				}).catch((e)=>{
					this.$Message.error('获取业务场景下角色失败');
					reject(e);
					this.$Spin.hide();
				})
			});
		},
		ok() {
			this.$refs['formValidate'].validate(valid => {
				if (valid) {
					this.getBottonStatus('loading');
					this.$emit('linkGeneration', this.form, this.getBottonStatus);
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		cancel() {
			this.dialogVisibleInviteMembers = false;
			this.$emit('colseCancel');
		},
		onCopy() {
			console.log(this.form.link);
			// const _this = this;
			navigator.clipboard.writeText(this.form.link).then(
				()=> {
					/* clipboard successfully set */
					this.$Message.success('链接已复制');
					//ivu-message
					setTimeout(() => {
						let box = document.querySelector('.ivu-message');
						console.log(box);
						box && box.setAttribute('style', 'z-index:999999999');
					}, 200);
				},
				(error)=> {
					/* clipboard write failed */
					console.log('####clipboard write failed',error);
					// this.$Message.error(error);
					// alert(error);
					const copyText = this.form.link;
					const dom = document.getElementById('copyBtn');
					const clipboard = new ClipboardJS(dom, {
						text: () => copyText
					});
					clipboard.on('success', () => {
						console.log('Copied to clipboard!');
						// this.$Message.success('链接已复制');
						// setTimeout(() => {
						// 	let box = document.querySelector('.ivu-message');
						// 	console.log(box);
						// 	box && box.setAttribute('style', 'z-index:999999999');
						// }, 200);
					});
					clipboard.on('error', () => {
						this.$Message.success('链接复制失败');
						console.error('Copy to clipboard failed!');
					});
					// const inputElement = document.createElement('input');
					// inputElement.value = copyText;
					// document.body.appendChild(inputElement);
					// inputElement.select();
					// document.execCommand('copy');
					// inputElement.remove();
					this.$Message.success('链接已复制');
					setTimeout(() => {
						let box = document.querySelector('.ivu-message');
						console.log(box);
						box && box.setAttribute('style', 'z-index:999999999');
					}, 200);
				}
			).catch((error)=>{
				console.log('####clipboard write error',error);
				// const _this = this;
				// const copyText = this.form.link;
				// 	console.log('_this',_this.$refs.copyBtn);
				// 	const dom = document.getElementById('copyBtn');
				// 	const clipboard = new ClipboardJS(dom, {
				// 		text: () => copyText
				// 	});
				// 	clipboard.on('success', () => {
				// 		console.log('Copied to clipboard!');
				// 		this.$Message.success('链接已复制');
				// 		setTimeout(() => {
				// 			let box = document.querySelector('.ivu-message');
				// 			console.log(box);
				// 			box && box.setAttribute('style', 'z-index:999999999');
				// 		}, 200);
				// 	});
				// 	clipboard.on('error', () => {
				// 		this.$Message.success('链接复制失败');
				// 		console.error('Copy to clipboard failed!');
				// 	});
			});
		},
		getBottonStatus(value) {
			this.loadingStatus = value;
		}
	}
};
</script>

<style lang="less" scoped>
// .invite-members-container {}
.content-modal {
	position: relative;
	.head-box {
		text-align: center;
	}
	.title {
		font-size: 15px;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #333333;
		line-height: 21px;
	}

	.subtitle {
		font-size: 13px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #666666;
		margin-top: 14px;
	}
	.reuse-text {
		font-size: 13px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #666666;
		line-height: 18px;
		margin-top: 10px;
	}
	.switch {
		margin-left: 10px;
	}
	.form-box {
		margin-top: 20px;
		.text-box {
			font-size: 13px;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			line-height: 18px;
			margin-bottom: 8px;
			.title-name {
				color: #333333;
			}
			.not-required {
				color: #a1a1a1;
			}
		}
	}
	.copy-content {
		margin-top: 12px;
		margin-bottom: 0px;
	}
	.copy-btn {
		height: 40px;
		background: #252b48;
		border-radius: 4px;
		width: 100%;
		color: #ffffff;
	}

	.loading-box {
		// display: flex;
		// align-content: center;
		// justify-content: center;
		position: absolute;
		top: 194px;
		left: 117px;
		.demo-spin-col {
			width: 88px;
			height: 98px;
			background: #000000;
			border-radius: 8px;
			opacity: 0.56;
		}
	}
}
</style>
<style lang="less">
.content-modal .ivu-modal {
	margin-top: -50px;
	padding: 0px 15px;
}
.content-modal .ivu-switch-checked {
	border-color: #252b48;
	background-color: #252b48;
}
.form-box .input-background .ivu-input {
	background-color: #f6f6f6;
	border-radius: 4px;
	height: 40px;
}
.form-box .dataTime-input-background .ivu-input {
	background-color: #f6f6f6;
	border-radius: 4px;
	height: 40px;
	text-align: left;
	padding-left: 1px;
}
.form-box .ivu-input-prefix i,
.ivu-input-suffix i {
	margin-top: 3px;
}
.form-box .ivu-input-with-suffix {
	padding-right: 0;
}
.form-box .ivu-input-suffix {
	left: auto;
	right: -8px;
}
.form-box .ivu-icon-ios-close-circle:before {
	content: none;
	display: none;
}

.form-box .input-link .ivu-input {
	height: 64px;
	border-radius: 4px;
	border: 1px solid #efeff6;
	text-align: center;
	background-color: #fff;
}

.form-box .active-font .ivu-input {
	height: 64px;
	border-radius: 4px;
	border: 1px solid #efeff6;
	text-align: center;
	background-color: #fff;
	font-size: 13px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #333333;
	line-height: 18px;
}

.content-modal .ivu-modal-footer {
	font-size: 15px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	line-height: 21px;
	text-align: center;
	margin-top: 8px;
	padding: 0;
	position: relative;
	.colse-btn {
		color: #a7a7a7;
		position: absolute;
		top: 20px;
		left: 80px;
	}
	.vertical-line {
		width: 1px;
		height: 55px;
		background-color: #efefef;
		display: inline-block;
	}
	.link-btn {
		// color: #a7a7a7;
		color: #252b48;
		position: absolute;
		top: 20px;
		left: 230px;
	}
	.grey-btn {
		color: #a7a7a7;
		position: absolute;
		top: 20px;
		left: 230px;
		pointer-events: none;
	}
	.generated-btn {
		color: #a7a7a7;
		position: absolute;
		top: 20px;
		left: 230px;
		pointer-events: none;
	}
}
</style>

<style>
.ivu-spin-show-text .ivu-spin-dot {
	display: inline-block;
}
.demo-spin-icon-load {
	animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
	from {
		transform: rotate(0deg);
	}
	50% {
		transform: rotate(180deg);
	}
	to {
		transform: rotate(360deg);
	}
}
.demo-spin-col {
	height: 100px;
	position: relative;
	border: 1px solid #eee;
}
.load-text {
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #ffffff;
	line-height: 20px;
}
</style>
